package de.hsma.srn.controller;

import de.hsma.srn.interfaces.Controller;
import de.hsma.srn.model.account.DomainModel;

/**
 * Controller FOR THE LOGIN VIEW, MANAGES THE CHANGES OF PANELS and login/logoff
 * @author tobia_000
 *
 */
public class MainController extends Controller {
	/*
	 * Members
	 */
	private DomainModel mDomain;
	private KeyBoxController mKeyBoxController;
	
	
	/*
	 * Getter & Setter
	 */
	/**
	 * Returns the keyBoxController for further working in the views.
	 * A keyboxController exists only if an user is logged in.
	 * Otherwise the return of this method and the object itself will be null!
	 * BE CAREFULL!
	 * @return Keyboxcontroller or null if no user is logged in
	 */
	public KeyBoxController getKeyBoxController() {
		if(this.mKeyBoxController!=null) {
			return this.mKeyBoxController;
		}
		return null;
	}
	
	
	/*
	 * Constructors
	 */
	public MainController(DomainModel domain) {
		this.mDomain = domain;
		this.mDomain.setController(this);
	}
	
	
	/*
	 * Methods (VIEW CODER SEE HERE)
	 */
	/**
	 * Logon the user with the given username and password
	 * @param username
	 * @param password
	 */
	public void login(String username, String password) {
		System.out.println("[CONTROLLER] Versuche User mit " + username + " und " + password + " anzumelden ...");
		if(this.mDomain.login(username, password)) {
			this.mKeyBoxController = new KeyBoxController(this.mDomain);
			System.out.println("[CONTROLLER] Login erfolgreich, benachrichtige alle Zuhoerer ...");
		}
		this.notifyListeners(this.mDomain);
	}
	/**
	 * Logout the user
	 */
	public void logout() {
		if(this.mDomain.logout()) {
			this.notifyListeners(this.mDomain);
		}
	}
	/**
	 * Validate the given username and look for duplicates
	 * @param username to validate
	 * @return true if username is valid
	 */
	public boolean validateUsername(String username) {
		if(username.length() >= 2 && this.mDomain.getUserList().get(username) == null) {
			return true;
		}
		return false;
	}
	/**
	 * Validate the given password
	 * @param password
	 * @return true if password is valid
	 */
	public boolean validatePassword(String password) {
		if(password.length() >= 5) {
			return true;
		}
		return false;
	}
	/**
	 * Register the user with the given username and password
	 * @param username to register the user with
	 * @param password to register the user with
	 */
	public void registerUser(String username, String password) {
		this.mDomain.register(username, password);
		this.notifyListeners(this.mDomain);
	}

	public void update() {
		if(!this.mDomain.isLoggedIn()) {
			this.notifyListeners(this.mDomain);
		}
	}
}
